<?php

namespace App\Supports\Payment\Methods\Goldcoin;

use Carbon\Carbon;
use App\Models\Order;
use App\Events\OrderPaidEvent;
use Illuminate\Support\Facades\DB;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodPay;

class PayOrder extends Method implements MethodPay
{
	protected function isCoinEnough($order)
	{
		return $order->user->isGoldCoinsEnough($order->total_amount);
	}

	public function validate($order = null)
	{
		if ($order->isPaid()) {
			fail('目标订单已支付');
		}
		if ($order->isClosed()) {
			fail('目标订单已关闭');
		}
		if ($order->isCancelled()) {
			fail('目标订单已取消');
		}
		if (!$this->isCoinEnough($order)) {
			fail('可用账户余额不足');
		}
	}

	public function info($order = null) {}

	public function pay($order = null)
	{
		$this->validate($order);

		return DB::transaction(function () use ($order) {
			$order = Order::lockForUpdate()->find($order->id);
			$order->update(['paid_at' => Carbon::now(), 'paid_method' => 'goldcoin']);
			$coins = $order->total_amount;
            $data = ['order_id' => $order->id];
            account_coins($order->user)->minusOrderPaid($coins, $data);
			event(new OrderPaidEvent($order));
			$order->unsetRelations();
			return $order;
		});
	}
}
